package org.scohen.juploadr;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

public class PropsDelta {

    public PropsDelta(String newFile, String oldFile, String toFix) throws FileNotFoundException, IOException {
        Properties newest = new Properties();
        Properties old = new Properties();
        Properties fix = new SortedProperties();
        newest.load(new FileInputStream(new File(newFile)));
        old.load(new FileInputStream(new File(oldFile)));
        fix.load(new FileInputStream(new File(toFix)));
        
        Set<Object> allProps = new LinkedHashSet<Object>();
        allProps.addAll(newest.keySet());
        allProps.addAll(old.keySet());

        Iterator keys = allProps.iterator();
        List<String> changedProps = new LinkedList<String>();
        List<String> unchangedProps = new LinkedList<String>();
        
        while (keys.hasNext()) {
            String key = (String) keys.next();
            String val1 = newest.getProperty(key);
            String val2 = old.getProperty(key);
            
            if (newest.containsKey(key) && !old.containsKey(key)) {
                System.out.println("+ " + key);
                changedProps.add(key);
            } else if (old.containsKey(key) && !newest.containsKey(key)) {
                System.out.println("- " + key);
                fix.remove(key);
            } else if(val1 != null && val2 != null && !val1.equals(val2)) {
                System.out.println("~ " + key);
                changedProps.add(key);
            } else {
                unchangedProps.add(key);
            }
        }
        
        Iterator iter = unchangedProps.iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            fix.setProperty(key, fix.getProperty(key));
        }
        iter = changedProps.iterator();
        fix.setProperty("=--------======EDIT BELOW THIS LINE======--------", "");
        while(iter.hasNext()) {
            String propName = (String) iter.next();
            fix.remove(propName);
            fix.setProperty(propName, newest.getProperty(propName));
        }
        fix.store(new FileOutputStream(new File(toFix + ".fixed")), "");
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        if (args.length != 3) {
            System.out.println("Usage: PropsDelta newFile oldFile fileToFix");
            System.exit(1);
        }
        new PropsDelta(args[0], args[1],args[2]);
    }
}
